#include <iostream>
#include <vector>
#include <map>
using namespace std;

#include "thirdparty/json.hpp"
using json = nlohmann::json;

void func1()
{
    // json序列化
    json js;
    js["id"] = 12;
    js["name"] = "zhang san";
    js["age"] = {1, 2, 3};
    // 添加对象
    js["msg"]["zhang san"] = "hello world";
    js["msg"]["liu shuo"] = "hello china";
    // 上面等同于下面这句一次性添加数组对象
    js["msg"] = {{"zhang san", "hello world"}, {"liu shuo", "hello china"}};
    cout << js << endl;

    // 容器序列化
    // 直接序列化一个vector容器
    vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(5);
    js["list"] = vec;
    cout << js << endl;

    // 直接序列化一个map容器
    map<int, string> m;
    m.insert({1, "abc"});
    m.insert({2, "def"});
    m.insert({3, "ghi"});
    js["path"] = m;
    cout << js << endl;
}

void func2()
{
    // json反序列化
    // 先模拟构造一个json对象
    json js;
    js["id"] = 12;
    js["age"] = {1, 2, 3};
    js["name"] = "zhang san";
    js["msg"]["zhang san"] = "hello world";
    js["msg"]["liu shuo"] = "hello china";
    vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(5);
    js["list"] = vec;
    map<int, string> m;
    m.insert({1, "abc"});
    m.insert({2, "def"});
    m.insert({3, "ghi"});
    js["path"] = m;

    // 将json对象序列化为一个字符串
    string jsonstr = js.dump();
    // 下面两句打印结果都是一样的
    // cout << js  << endl;
    // cout << jsonstr  << endl;

    // // 模拟从网络接收到json字符串，通过json::parse函数把json字符串专程json对象
    json js2 = json::parse(jsonstr);
    cout << js2["name"] << endl;
    cout << js2["id"] << endl;
    cout << js2["age"] << endl;
    cout << js2["list"] << endl;

    // 直接反序列化vector容器
    vector<int> v = js2["list"];
    for (int val : v)
    {
        cout << val << " ";
    }
    cout << endl;

    // 直接反序列化map容器
    map<int, string> m2 = js2["path"];
    for (auto &p : m2)
    {
        cout << p.first << " " << p.second << endl;
    }
    cout << endl;
}

int main()
{
    // func1();
    func2();
    return 0;
}